#!/bin/bash -x

kata_coco_top_dir="$HOME/workspace/CoCo/"

kata_containers_repo_url="https://gitee.com/hanliyang-kata-coco/kata-containers.git"
kata_containers_repo_branch="3.13.0-hygon"
kata_containers_repo_dir="${kata_coco_top_dir}/kata-containers"

if [ ! -e ${kata_containers_repo_dir} ]; then
  git clone ${kata_containers_repo_url} \
    -b ${kata_containers_repo_branch} \
    ${kata_containers_repo_dir}
fi

# check and install yq if not exist
echo "Check and Install yq"
command yq > /dev/null
if [ $? -ne 0 ]; then
  DEBUG="y" ${kata_containers_repo_dir}/ci/install_yq.sh
  echo 'export PATH=$PATH:$HOME/go/bin/' >> $HOME/.profile
  source $HOME/.profile
fi

# install libseccomp
echo "Install libseccomp"
rm -rf /tmp/libseccomp.* /tmp/gperf.*
export libseccomp_install_dir=$(mktemp -d -t libseccomp.XXXXXXXXXX)
export gperf_install_dir=$(mktemp -d -t gperf.XXXXXXXXXX)
${kata_containers_repo_dir}/ci/install_libseccomp.sh "${libseccomp_install_dir}" "${gperf_install_dir}"

install_kata_agent_deps () {
  echo "Install kata-agent dependencies"
  sudo apt install -y musl-tools \
    libclang-dev protobuf-compiler
}

install_kata_agent_deps

build_install_kata_agent () {
  echo "Build and Install kata-agent"

  ulimit -n 65536 # fs.nofile

  export LIBSECCOMP_LINK_TYPE=static
  export LIBSECCOMP_LIB_PATH="${libseccomp_install_dir}/lib"

  export ARCH="$(uname -m)"
  if [ "$ARCH" = "ppc64le" -o "$ARCH" = "s390x" ]; then export LIBC=gnu; else export LIBC=musl; fi
  [ "${ARCH}" == "ppc64le" ] && export ARCH=powerpc64le
  rustup target add "${ARCH}-unknown-linux-${LIBC}"

  pushd ${kata_containers_repo_dir}/src/agent

  # INIT=no
  make clean
  cargo update -p image-rs
  make LIBC=${LIBC} SECCOMP=yes AGENT_POLICY=yes INIT=no
  sudo rm -rf /dev/shm/kata-agent || true
  mkdir -p /dev/shm/kata-agent/
  make install DESTDIR=/dev/shm/kata-agent/ LIBC=${LIBC} INIT=no
  pushd /dev/shm/kata-agent
  if [ ! -e kata-agent.tar.xz ]; then
    tar -cvJf kata-agent.tar.xz usr/
  fi
  popd # /dev/shm/kata-agent

  # INIT=yes
  make clean
  cargo update -p image-rs
  make LIBC=${LIBC} SECCOMP=yes AGENT_POLICY=yes INIT=yes
  sudo rm -rf /dev/shm/kata-agent-init || true
  mkdir -p /dev/shm/kata-agent-init
  make install DESTDIR=/dev/shm/kata-agent-init/ LIBC=${LIBC} INIT=yes
  pushd /dev/shm/kata-agent-init
  if [ ! -e kata-agent-init.tar.xz ]; then
    tar -cvJf kata-agent-init.tar.xz usr/
  fi
  popd # /dev/shm/kata-agent-init

  popd # ${kata_containers_repo_dir}
}

build_install_kata_agent
